<% layout('device_header') -%>
<% stylesheet('/css/map.css') -%>
<% stylesheet('http://cdn.leafletjs.com/leaflet-0.4/leaflet.css') -%>
<% stylesheet('/leaflet/leaflet.label.css') -%>
<% stylesheet('/leaflet/leaflet.draw.css') -%>
<% stylesheet('/leaflet/leaflet.pushmessage.css') -%>
<% stylesheet('/leaflet/leaflet.pushmessage_history.css') -%>

<% script('https://maps.googleapis.com/maps/api/js?key=AIzaSyA9hZO1Yz7lBgNJiKfu5qznUxk2EhuqbxI&sensor=true') -%>
<% script('http://localhost:3000/socket.io/socket.io.js') -%>
<% script ('http://cdn.leafletjs.com/leaflet-0.4/leaflet.js') -%>
<% script('/leaflet/leaflet.label.js') -%>
<% script('/leaflet/leaflet.zoomfs.js') -%>
<% script('/leaflet/AnimatedMarker.js') -%>
<% script('/leaflet/raphael/rlayer-src.js') -%>
<% script('/leaflet/raphael/raphael-min.js') -%>
<% script ('/leaflet/leaflet.draw.js') -%>
<% script ('/leaflet/leaflet.pushmessage.js') -%>
<% script ('/leaflet/leaflet.pushmessage_history.js') -%>

<p id="regid" style="display:none">APA91bF9Q7A9ZT02xOLWTNTgn3Bzd9BSIR1gh8tMd5S8dBC3BoPD0hnZeUkB0JKVyzawsuZTNJPDmvLcER9I7c52xFtuFbqwRvQ-o8lWa9pd64CtoYP_F1YhglLTNWLNH6TlRMu5zhdB</p>
<p id="deviceid" style="display:none"> <%= device[0].id %> </p>
<p style="display:none"> <%= device[0].push_notification_id %> </p>
<div >
	<h3 class="pull-left" ><span style="color:blue"><%= device[0].name %>'s</span> movement.</h3>	
	<h3 class="pull-right"><a href="#" OnClick="getcurrentlocation();">Get current location</a></h3>
</div>

<table class="table">
	<tr>
		<td width="75%" style="border-top:none;padding:0px;">
			<div id="map" class="leaflet-container leaflet-fullscreen">
		</td>
		<td style="border-top:none;padding-top:0px" width="30%" height="500px" id="table_location"> 
			<div>
		      <ul class="nav nav-tabs">
		      	<li class="active"><a href="#current_delivery" onClick="rightnow()" data-toggle="tab">Right Now</a></li>
		      	<li><a href="#delivery_history" onClick="deliveriesnow()" data-toggle="tab">Deliveries</a></li>		         
		        <li><a href="#messages_history" data-toggle="tab">Reminders</a></li>
		      </ul>
		      <div class="tabbable">
		        <div class="tab-content">
		          <div class="tab-pane active" id="current_delivery"></div>
		          <div class="tab-pane" id="delivery_history"></div>
		          <div class="tab-pane" id="messages_history"></div>		            
		        </div>
		      </div> <!-- /tabbable -->      
		    </div>

		</td>
	</tr>
</table>

<form class = "well">
    <b>Create new location</b>
    <div>Latitude: <input type='text' class="span4" id='latitude' value=''></div>
    <div>Longitude: <input type='text'  class="span4" id='longitude' value=''></div>
    <div>Accuracy: <input type='text' class="span4" id='accuracy' value=''></div>
    <button class="btn btn-primary" id='save'>Save</button>
</form>

<div id="alertmodal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-header">
        <h3>Delete Device</h3>
      </div>
      <div id="alertbody" class="modal-body">

      </div>
	 <div class="modal-footer">
			<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>	 
    </div>	      
</div> 
<script type="text/javascript"> 

var pushMessageSocket;
var locationSocket;
$(document).ready(function () {
	
	pushMessageSocket  = io.connect('http://localhost:3000/push_messages');
	locationSocket = io.connect('http://localhost:3000/locations');

	pushMessageSocket.socket.on('error', function (reason){
		alert('Unable to connect Socket.IO'+reason);
	});

	pushMessageSocket.on('connect', function (){	  
		socket.emit("device", { device_id:<%= device[0].id %> });
	});

  	pushMessageSocket.on('populate', function(data) {
    	alert( ' ######### pushMessageSocket message ############## '+data);
    });

    pushMessageSocket.on('update', function (data) {        
        alert( ' ######### pushMessageSocket new update ############## '+JSON.stringify(data));
    });

	locationSocket.socket.on('error', function (reason){
		alert('Unable to connect Socket.IO'+reason);
	});

	locationSocket.on('connect', function (){	  
		socket.emit("device", { device_id:<%= device[0].id %> });
	});

  	locationSocket.on('populate', function(data) {
    	alert( ' ######### locationSocket message ############## '+data);
    });

    locationSocket.on('update', function (data) {        
        alert( ' ######### locationSocket new update ############## '+JSON.stringify(data));
    });    

	/*var mapOptions = {
	  center: new google.maps.LatLng(-34.397, 150.644),
	  zoom: 8,
	  mapTypeId: google.maps.MapTypeId.ROADMAP,
	  scrollwheel: false
	};

	var map = new google.maps.Map(document.getElementById("map"),mapOptions); */

	setMapDetails();

	setTimeout('getAllDeliveries()',500);
	$("#current_delivery").html('No Active Current Delivery');
});

var map = L.map('map',{
    center: [39.74739, -105],
    zoom: 16,
    scrollWheelZoom: false,
    zoomControl: false,
    doubleClickZoom: false
});

var drawControl = new L.Control.Draw({
  marker: false,
  rectangle: false,
  polyline: false,
  polygon: false,
  cricle: {
    shapeOptions: {
        clickable: true
    }
  }
});

var pushMessageControl = new L.Control.Push();
var pushHistoryControl = new L.Control.Push_History();
var circleControlAdded = true;
var currDelivery_id = 0; // To hold the current active delivery.

setMapDetails = function() {
	
    
    var zoomFS = new L.Control.ZoomFS(); 
    map.addControl(zoomFS);

    L.tileLayer('http://{s}.tile.cloudmade.com/9c35b088a373420599be6e705d52a055/997/256/{z}/{x}/{y}.png', {
    	attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
	    maxZoom: 18
	}).addTo(map);		


    map.on('enterFullscreen', function(){
  		if(window.console) window.console.log('enterFullscreen');
	});

	map.on('exitFullscreen', function(){
	  if(window.console) window.console.log('exitFullscreen');
	});

    var drawnItems = new L.LayerGroup();
    // TODO:: Restrict user from drawing a circle if a circle is already present on map.
    var pushPopup = null;
    var pushCircle;
    map.on('draw:circle-created', function (e) {
      drawnItems.addLayer(e.circ);

      pushCircle = e.circ;
      e.circ.on('click', function(e) {
        pushPopup = popup
            .setLatLng(e.latlng)
            .setContent('<div style="padding:10px" <h3><b>Send Message</b></h3> <br/><br/>'+ 
              '<input id="push_message" type="text" size ="30"/> <br/>'+
              '<button id="sendmessage" onClick="sendPopupPushmessage()" class="btn btn-success">'+
              '<i class="icon-envelope icon-white"></i> Send </button></div><br/>'+ 
              'You clicked in circle at' + e.latlng.toString())
            .openOn(map);

      });
      setTimeout(function() {
          //Remove the circle if user does nothing for 20secs.
          checkToRemovePushCircle();
        }, 10000); 
    });

    map.addLayer(drawnItems);
    map.addControl(drawControl);
    map.addControl(pushMessageControl);

    sendPopupPushmessage = function() {
      var message = $("#push_message").val();
      alert(message);
    };

    checkToRemovePushCircle = function() {
        drawnItems.removeLayer(pushCircle);
        $("#popup").remove();
        //alert('check to remove');
    	//setTimeout( checkToRemovePushCircle, 10000);
    }
}

var currentDeliveryLayer = null;

rightnow = function() {

	if( !circleControlAdded ) {
		map.addControl(drawControl);
		map.addControl(pushMessageControl);
		map.removeControl(pushHistoryControl);
		circleControlAdded = true;
	}

	if(geoJSONLayer != null) {
		map.removeLayer(geoJSONLayer);
		geoJSONLayer = null;
	}


	var currentMkr = L.marker([39.7471494,-104.9998241]).bindPopup('This is Littleton, CO.').bindLabel('I am here', { noHide: true }).showLabel();
	currentDeliveryLayer = L.layerGroup([currentMkr]);

    var bikeIcon = L.icon({
      iconUrl: '/leaflet/bike.png',
      iconSize: [25, 39],
      iconAnchor: [12, 39],
      shadowUrl: null
    });

    var line = L.polyline([[39.7471494,-104.9998241],[39.7502833,-104.9983545],[39.7444271,-104.9963919]]);

    var animatedMarker = L.animatedMarker(line.getLatLngs(), {
      autoStart: false,
      icon: bikeIcon,
      onEnd: function() {
        $(this._shadow).fadeOut();
        $(this._icon).fadeOut(1000, function(){
          map.removeLayer(this);
        });
      }
    });

    //currentDeliveryLayer.addLayer(animatedMarker);
     map.addLayer(animatedMarker);
    $(animatedMarker._icon).hide().fadeIn(500, function(){
      animatedMarker.start();
    });
    
    setTimeout(function() {
      // Stop the animation
      animatedMarker.stop();
    }, 8000); 

    var popup = L.popup();
        
    function onMapClick(e) {
	    popup
	        .setLatLng(e.latlng)
	        .setContent("You clicked the map at " + e.latlng.toString())
	        .openOn(map);

	      var p = new R.Pulse(
	          e.latlng, 
	          6,
	          {'stroke': '#2478ad', 'fill': '#30a3ec'}, 
	          {'stroke': '#30a3ec', 'stroke-width': 3});

	      map.addLayer(p);

	      setTimeout(function() {
	        map.removeLayer(p);
	      }, 8000);   

    }

    //map.on('click', onMapClick);
    currentDeliveryLayer.addTo(map);
}

deliveriesnow = function() {
	if( circleControlAdded ) {
		map.removeControl(drawControl);
		map.removeControl(pushMessageControl);
		map.addControl(pushHistoryControl);
		circleControlAdded = false;		
	}	

	if(currentDeliveryLayer != null) {
		map.removeLayer(currentDeliveryLayer);
		currentDeliveryLayer = null;
	}
}

showAlert = function(msg) {
	$('#alertbody').html('<p>'+msg+'</p>');
	$('#alertmodal').modal('show');
}

sendPushMessage = function(pushMessage) {	
	/*var pushMessage = $("#message").val();
	if( pushMessage.length == 0) {
		alert(' Please enter a message');
		return;
	} */
	

	if( currDelivery_id == 0 ) {
		alert(' Sorry no active delivery to send message.');
		return;
	}
	
	var notificationId = $("#regid").html();
	var deviceid = $("#deviceid").html();
	
	$.ajax({
	        url: "/delivery/"+currDelivery_id+"/push_message",
	        data: { 
	        	'push_notification_id': notificationId, 
      			'push_message': pushMessage,
      			'latitude':'1.22323231',
      			'longitude':'0.9281121',
      			'accuracy':'1000'        		
    		},
	        type: "post",
	        success: function(response, textStatus, jqXHR){
	            // log a message to the console
	            var result = JSON.parse(response);
	            if( result[0].status == '200') {
	              	showAlert(' Successfully sent the message');
	            } else if( result[0].status == '400') {
	            	showAlert(' ERROR: Sending message '+result[1].error);
	            }
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	showAlert(" Error while sending push message "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	    }); // End of ajax
}

getPushMessagesHistory = function(delivery_id) {
	
	$.ajax({
	        url: "/delivery/"+delivery_id+"/push_messages",
	        type: "get",
	        success: function(response, textStatus, jqXHR){
	        	var result = response;
	            if( result[0].status == '200') {
	              	parsePushHistoryResponse(response);
	            } else if( result[0].status == '400' || result[0].status == '422') {
	            	$("#messages_history").html(' ERROR: Sending message '+result[1].error);
	            }	        		            
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	showAlert(" Error while getting message history "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	}); // End of ajax
}

parsePushHistoryResponse = function(response) {

	var result = JSON.parse(response[1]);
	if(result.length == 0) {
		$("#messages_history").html("<p> No Messages sent </p>");
		return;
	} 

	var html="";
	for(var i = 0; i< result.length; i++){
		var message = result[i].push_message;
		var created_at = parseInt(result[i].created_at);	
		var sender = result[i].sender;
		if( sender == 'server') {
			html += '<div align="left" style="margin:5px;background:#99cc66;padding:5px">';
			html += '<img src="/images/server_sent.png" height="22" width="22">';			
		} else if( sender == 'user') {
			html += '<div align="right" style="margin:5px;background:#99cccc;padding:5px">';
		}
		
		html += " <h3>"+message+"</h3> <small> ";
		var a = new Date(created_at);
	  	var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	  	var year = a.getFullYear();
	  	var month = months[a.getMonth()];
	  	var date = a.getDate();
	  	var hour = a.getHours();
	  	var min = a.getMinutes();
	  	var sec = a.getSeconds();
	  	var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
	  	html += time+"</small>";
	  	if(sender == 'user')
	  		html+='<img src="/images/server_received.png" height="22" width="22">';	
	  	html += "</div>";
	}
	pushHistoryControl.addData(html);
	$("#messages_history").html(html);
}

getAllDeliveries = function() {
		
	var deviceid = $("#deviceid").html();
	$.ajax({
	        url: "/device/"+deviceid+"/deliveries",
	        type: "get",
	        success: function(response, textStatus, jqXHR){
	        	var result = response;
	            if( result[0].status == '200') {
	              	parseDeliveriesResponse(response);
	            } else if( result[0].status == '400' || result[0].status == '422') {
	            	$("#delivery_history").html(' ERROR: Fetching deliveries '+result[1].error);
	            }	        		            
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	showAlert(" Error while Fetching deliveries "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	}); // End of ajax
}

parseDeliveriesResponse = function(response) {
	
	//movement_history
	var result = JSON.parse(response[1]);
	if(result.length == 0) {
		$("#delivery_history").html("<p> No deliveries found. </p>");
		return;
	} 

	var html="";
	for(var i = 0; i< result.length; i++){
		var started_at = parseInt(result[i].started_at);	
		var delivered_at = parseInt(result[i].delivered_at);	
		var delivery_content = result[i].delivery_content;
		var bill_number = result[i].bill_number;
		var id = result[i].id;


		var a = new Date(started_at);
	  	var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	  	var year = a.getFullYear();
	  	var month = months[a.getMonth()];
	  	var date = a.getDate();
	  	var hour = a.getHours();
	  	var min = a.getMinutes();
	  	var sec = a.getSeconds();
	  	var startTime = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
		

		a = new Date(delivered_at);
	  	months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	  	year = a.getFullYear();
	  	month = months[a.getMonth()];
	  	date = a.getDate();
	  	hour = a.getHours();
	  	min = a.getMinutes();
	  	sec = a.getSeconds();
	  	var endTime = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
	  	
	  	if( delivered_at == 0) {
	  		// Treat this delivery as current delivery.
	  		currDelivery_id = id;

	  		var currhtml = '<div style="margin:5px;background:#d29911;padding:5px">';
	  		currhtml += '<h4>'+delivery_content+'</h4>';
	  		currhtml += " <h4>"+bill_number+"</h4><small>";
			currhtml += " <small>"+startTime+"</small><br/>";
			currhtml += " <small>"+endTime+"</small></div>";
			$("#current_delivery").html(currhtml);

	  	} else {
			
			html += '<div onClick="onClickDelivery('+id+')"';
			html += 'style="margin:5px;background:#d29911;padding:5px"> <h4>'+delivery_content+"</h4>";
			html += "<h4>"+bill_number+"</h4>";
			html += "<small>"+startTime+"</small><br/>";
			html += "<small>"+endTime+"</small>";
	  		html += "</div>";
	  	}
	}
	$("#delivery_history").html(html);
}

onClickDelivery= function(delivery_id){
	getPushMessagesHistory(delivery_id);
	getLocationPoints(delivery_id);
	// Get list of locations for that delivery.
}

getLocationPoints = function(delivery_id) {
		
	$.ajax({
	        url: "/delivery/"+delivery_id+"/location_movements",
	        type: "get",
	        success: function(response, textStatus, jqXHR){
	        	var result = response;
	            if( result[0].status == '200') {
	              	parseGeoJSON(response[1]);
	            } else if( result[0].status == '400' || result[0].status == '422') {
	            	$("#delivery_history").html(' ERROR: Fetching location movements '+result[1].error);
	            }	        		            
	        },
	        error: function(jqXHR, textStatus, errorThrown){
	        	showAlert(" Error while Fetching location movements "+testStatus+"  : "+errorThrown);
	        },
	        complete: function(){
	            // enable the inputs
	        }
	}); // End of ajax
} 

var geoJSONLayer = null;
parseGeoJSON = function(geoJSON) {

	function onEachFeature(feature, layer) {
	    if (feature.properties && feature.properties.popupContent) {
	        layer.bindPopup(feature.properties.popupContent);
	    }
	}
	
	/*alert(JSON.stringify(geoJSON.features[0].geometry.coordinates[0]));
	alert(JSON.stringify(geoJSON.features[0].geometry.coordinates[1]));
	alert(JSON.stringify(geoJSON.features[geoJSON.features.length-2].geometry.coordinates[0]));
	alert(JSON.stringify(geoJSON.features[geoJSON.features.length-2].geometry.coordinates[1])); */

	var startLatLng = [];
	var endLatLng = [];

	startLatLng.push(geoJSON.features[0].geometry.coordinates[1]);
	startLatLng.push(geoJSON.features[0].geometry.coordinates[0]);

	endLatLng.push(geoJSON.features[geoJSON.features.length-2].geometry.coordinates[1]);
	endLatLng.push(geoJSON.features[geoJSON.features.length-2].geometry.coordinates[0]);

	alert(JSON.stringify(startLatLng))
	alert(JSON.stringify(endLatLng));

	
	// Add the start and end markers with labels.
	var startMkr = L.marker(startLatLng).bindLabel('Start', { noHide: true }).showLabel();
	var endMkr = L.marker(endLatLng).bindLabel('Start', { noHide: true }).showLabel();
	geoJSONLayer = L.layerGroup([startMkr,endMkr]);

	//geoJSONLayer.add(L.marker(startLatLng).bindLabel('Start', { noHide: true }).showLabel());	
	//geoJSONLayer.add(L.marker(endLatLng).bindLabel('Start', { noHide: true }).showLabel());

	//L.marker(startLatLng).bindLabel('End', { noHide: true }).addTo(map).showLabel();	
	//L.marker(endLatLng).bindLabel('End', { noHide: true }).addTo(map).showLabel();	

    var geoJSON1 = L.geoJson(geoJSON, {
	    onEachFeature: onEachFeature,
		pointToLayer: function (feature, latlng) {

			if(feature.properties.style)
    	    	return L.circleMarker(latlng, feature.properties.style);
    	    else
    	    	return;
	    }      
    }).bindLabel('Route to end point');
    geoJSONLayer.addLayer(geoJSON1);
    geoJSONLayer.addTo(map);
}

getcurrentlocation = function() {
	alert('get current location');

}
</script>  
